// axios封装
import axios from "axios";

const baseInstance = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
  },
});

//拦截器
baseInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("auth_token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

baseInstance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response.data;
    } else {
      ElMessage.error(response.data.message);
      return Promise.reject(response.data);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

class request {
  static get(url: string, params: any) {
    return baseInstance.get(url, { params });
  }
  static post(url: string, data: any) {
    return baseInstance.post(url, data);
  }
  static put(url: string, data: any) {
    return baseInstance.put(url, data);
  }
  static delete(url: string) {
    return baseInstance.delete(url);
  }
  static patch(url: string, data: any) {
    return baseInstance.patch(url, data);
  }
}

export default request;
